<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="服务名称" prop="serviceName" style="width: 100%;">
              <el-input style="width: 100%;" v-model="queryParams.serviceName" placeholder="请输入服务名称" clearable
                @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="路由URL" prop="routeUrl" style="width: 100%;">
              <el-input v-model="queryParams.routeUrl" placeholder="请输入路由URL" style="width: 100%;" clearable
                @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="路由类型" prop="routeType" style="width: 100%;">
              <el-select v-model="queryParams.routeType" placeholder="请选择路由类型" clearable style="width: 100%;">
                <el-option v-for="item in routeTypeOptions" :key="item.dictValue" :label="item.dictLabel"
                  :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="HTTP方法" prop="httpMethod" style="width: 100%;">
              <el-select v-model="queryParams.httpMethod" placeholder="请选择HTTP方法" clearable style="width: 100%">
                <el-option v-for="item in httpMethodOptions" :key="item.dictValue" :label="item.dictLabel"
                  :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" class="mt-2">
          <el-col :span="6">
            <el-form-item label="路由状态" prop="status" style="width: 100%;">
              <el-select v-model="queryParams.status" placeholder="请选择路由状态" clearable style="width: 100%">
                <el-option v-for="item in routeStatusOptions" :key="item.dictValue" :label="item.dictLabel"
                  :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="创建时间" prop="createTime" style="width: 100%">
              <el-date-picker v-model="queryParams.createTime" type="daterange" range-separator="至"
                start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="6" style="text-align: left;">
            <el-button type="primary" @click="handleQuery">
              <el-icon>
                <Search />
              </el-icon>搜索
            </el-button>
            <el-button @click="resetQuery">
              <el-icon>
                <Refresh />
              </el-icon>重置
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="table-card mt-2">
      <el-button type="primary" @click="handleAdd">
        <el-icon>
          <Plus />
        </el-icon>新增路由
      </el-button>
      <el-button type="danger" :disabled="multiple" @click="handleDelete">
        <el-icon>
          <Delete />
        </el-icon>批量删除
      </el-button>
      <el-button @click="handleExport">
        <el-icon>
          <Download />
        </el-icon>导出
      </el-button>

      <!-- 数据表格 -->
      <el-table :data="routeList" @selection-change="handleSelectionChange" border stripe class="mt-2">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="ID" prop="id" width="80" align="center" />
        <el-table-column label="服务名称" prop="serviceName" min-width="120" show-overflow-tooltip />
        <el-table-column label="路由URL" prop="routeUrl" min-width="200" show-overflow-tooltip />
        <el-table-column label="路由类型" prop="routeType" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getRouteTypeTag(row.routeType)">
              {{ getRouteTypeLabel(row.routeType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="HTTP方法" prop="httpMethod" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getMethodTag(row.httpMethod)">
              {{ getName(httpMethodOptions, row.httpMethod,'dictValue','dictLabel') }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="排序号" prop="sortNum" width="80" align="center" />
        <el-table-column label="状态" prop="status" width="100" align="center">
          <template #default="{ row }">
            <el-switch v-model="row.status" :active-value="1" :inactive-value="0" @change="handleStatusChange(row)" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="160" align="center">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">
              <el-icon>
                <Edit />
              </el-icon>编辑
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">
              <el-icon>
                <Delete />
              </el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" :before-close="handleCloseDialog">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" class="dialog-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="服务名称" prop="serviceName">
              <el-input v-model="form.serviceName" placeholder="请输入服务名称" maxlength="50" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="路由类型" prop="routeType">
              <el-select v-model="form.routeType" placeholder="请选择路由类型" style="width: 100%"
                @change="handleRouteTypeChange">
                <el-option v-for="item in routeTypeOptions" :key="item.dictValue" :label="item.dictLabel"
                  :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="路由URL" prop="routeUrl">
              <el-input v-model="form.routeUrl" placeholder="请输入路由URL（确保唯一）" maxlength="200" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="HTTP方法" prop="httpMethod">
              <el-select v-model="form.httpMethod" placeholder="请选择HTTP方法" style="width: 100%">
                <el-option v-for="item in httpMethodOptions" :key="item.dictValue" :label="item.dictLabel"
                  :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序号" prop="sortNum">
              <el-input-number v-model="form.sortNum" :min="0" :max="999" controls-position="right"
                style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="路由状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注信息" maxlength="500"
                show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <el-button @click="handleCloseDialog">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="dialog.loading">
          {{ dialog.title === '新增路由' ? '新增' : '保存' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'

// API引入
import {
  getRouteList,
  getRouteDetail,
  addRoute,
  updateRoute,
  deleteRoute,
  getPageTypeList,
  getRequestMethodList,
  getRouteStatusList
} from '@/api/sysManage/routeManage'

// 搜索表单引用
const queryFormRef = ref()
// 表单引用
const formRef = ref()

// 加载状态
const loading = ref(false)
// 选中数组
const ids = ref([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)

// 路由列表数据
const routeList = ref([])
// 总条数
const total = ref(0)

// 下拉选项数据
const routeTypeOptions = ref([])
const httpMethodOptions = ref([])
const routeStatusOptions = ref([])

// 搜索参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  serviceName: undefined,
  routeUrl: undefined,
  routeType: undefined,
  httpMethod: undefined,
  status: undefined,
  createTime: undefined
})

// 对话框配置
const dialog = reactive({
  visible: false,
  title: '',
  loading: false
})

// 表单数据
const form = reactive({
  id: undefined,
  serviceName: '',
  routeUrl: '',
  routeType: undefined,
  httpMethod: '',
  status: 1,
  sortNum: 0,
  remark: ''
})

// 表单验证规则
const rules = {
  serviceName: [
    { required: true, message: '服务名称不能为空', trigger: 'blur' },
    { min: 1, max: 50, message: '服务名称长度不能超过50个字符', trigger: 'blur' }
  ],
  routeUrl: [
    { required: true, message: '路由URL不能为空', trigger: 'blur' },
    { min: 1, max: 200, message: '路由URL长度不能超过200个字符', trigger: 'blur' }
  ],
  routeType: [
    { required: true, message: '路由类型不能为空', trigger: 'change' }
  ],
  httpMethod: [
    { required: true, message: 'HTTP方法不能为空', trigger: 'change' }
  ],
  sortNum: [
    { required: true, message: '排序号不能为空', trigger: 'blur' }
  ]
}

// 初始化数据
onMounted(() => {
  getList()
  loadSelectOptions()
})

// 加载下拉选项数据
const loadSelectOptions = async () => {
  try {
    const [pageTypeRes, methodRes, statusRes] = await Promise.all([
      getPageTypeList(),
      getRequestMethodList(),
      getRouteStatusList()
    ])

    routeTypeOptions.value = pageTypeRes.data || []
    httpMethodOptions.value = methodRes.data || []
    routeStatusOptions.value = statusRes.data || []
  } catch (error) {
    console.error('加载下拉选项失败:', error)
  }
}

// 获取路由列表
const getList = async () => {
  try {
    const res = await getRouteList(queryParams)
    routeList.value = res.rows || []
    total.value = res.total || 0
  } catch (error) {
    console.error('获取路由列表失败:', error)
    ElMessage.error('获取路由列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  queryParams.createTime = undefined
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = selection.length === 0
}

// 新增按钮操作
const handleAdd = () => {
  resetForm()
  dialog.visible = true
  dialog.title = '新增路由'
}

// 编辑按钮操作
const handleEdit = async (row) => {
  try {
    const res = await getRouteDetail(row.id)
    Object.assign(form, res.data)
    dialog.visible = true
    dialog.title = '编辑路由'
  } catch (error) {
    console.error('获取路由详情失败:', error)
    ElMessage.error('获取路由详情失败')
  }
}

// 删除按钮操作
const handleDelete = async (row) => {
  const routeIds = row.id ? [row.id] : ids.value
  if (routeIds.length === 0) {
    ElMessage.warning('请选择要删除的路由')
    return
  }

  try {
    await ElMessageBox.confirm(
      `是否确认删除选中的${routeIds.length}条数据？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const res = await deleteRoute(routeIds.join(','))
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 状态修改
const handleStatusChange = async (row) => {
  try {
    const text = row.status === 1 ? '启用' : '停用'
    await ElMessageBox.confirm(
      `确认要${text}"${row.serviceName}"吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const formData = { ...row }
    const res = await updateRoute(formData)
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('状态修改失败:', error)
      ElMessage.error('状态修改失败')
      // 恢复原状态
      row.status = row.status === 1 ? 0 : 1
    }
  }
}

// 路由类型变化处理
const handleRouteTypeChange = (value) => {
  // 可以根据路由类型做不同的处理
  console.log('路由类型变化:', value)
}

// 关闭对话框
const handleCloseDialog = () => {
  dialog.visible = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  formRef.value?.clearValidate()
  Object.assign(form, {
    id: undefined,
    serviceName: '',
    routeUrl: '',
    routeType: undefined,
    httpMethod: '',
    status: 1,
    sortNum: 0,
    remark: ''
  })
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    dialog.loading = true

    const formData = { ...form }
    let res

    if (form.id) {
      res = await updateRoute(formData)
    } else {
      res = await addRoute(formData)
    }

    dialog.visible = false
    getList()
  } catch (error) {
    console.error('表单提交失败:', error)
    if (error.errors) return // 验证错误不显示消息
    ElMessage.error('操作失败')
  } finally {
    dialog.loading = false
  }
}

// 导出按钮操作
const handleExport = () => {
  ElMessage.info('导出功能待实现')
}

// 工具函数
const formatDate = (dateString) => {
  if (!dateString) return '-'
  try {
    return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss')
  } catch {
    return dateString
  }
}

const getRouteTypeTag = (type) => {
  const typeMap = {
    '1': 'primary',
    '2': 'success'
  }
  return typeMap[type] || 'info'
}

const getRouteTypeLabel = (type) => {
  const option = routeTypeOptions.value.find(item => item.dictValue == type)
  return option ? option.dictLabel : type
}

const getMethodTag = (method) => {
  const methodMap = {
    '1': 'success',
    '2': 'primary',
    '3': 'warning',
    '4': 'danger'
  }
  return methodMap[method] || 'info'
}
</script>

<style scoped lang="scss">
.table-card {
  :deep(.el-card__header) {
    padding: 16px 20px;
  }

  :deep(.el-card__body) {
    padding: 0;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.card-actions {
  display: flex;
  gap: 8px;
}

.dialog-form {
  padding: 0 20px;
}

:deep(.el-table) {
  .cell {
    white-space: nowrap;
  }

  th {
    background: #f5f7fa;
    font-weight: 600;
  }
}

:deep(.el-pagination) {
  padding: 16px;
  justify-content: flex-end;
}

@media (max-width: 768px) {
  .app-container {
    padding: 10px;
  }

  .card-header {
    flex-direction: column;
    align-items: stretch;
    gap: 10px;
  }

  .card-actions {
    justify-content: flex-end;
  }
}
</style>